/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Base/Thread_WIN32.h"
#include "Base/Runnable.h"
#include "Global_Macros.h"


ThreadImpl::ThreadImpl(Runnable *runnable)
	: _id(0)
	, _handle(-1L)

	, _runnable(runnable)
{

}

ThreadImpl::~ThreadImpl(void)
{
	if (_handle != -1L) {
		CloseHandle((HANDLE)_handle);
	}
}

bool ThreadImpl::startImpl(void)
{
	MY_ASSERT(_handle == -1L);
	_handle = ::_beginthreadex(NULL, 0, ThreadImpl::proc,
		this, 0, (unsigned int*)&_id);
	return _handle != -1L;
}

void ThreadImpl::joinImpl(void)
{
	MY_ASSERT(_handle != -1L);
	if (_handle != -1L) {
		WaitForSingleObject(HANDLE(_handle), INFINITE);
	}
}

bool ThreadImpl::joinableImpl(void)
{
	return _handle != -1L;
}

unsigned int ThreadImpl::proc(void* arg)
{
	MY_ASSERT(arg != NULL);
	ThreadImpl* pth = static_cast<ThreadImpl*>(arg);
	pth->_runnable->run();
	return 0;
}